//
//  SHJudgeTools.m
//  YouTong
//
//  Created by chirui on 16/4/11.
//  Copyright © 2016年 chuirui_Shui. All rights reserved.
//

#import "SHJudgeTools.h"
#import "MBProgressHUD.h"
#import <CommonCrypto/CommonCrypto.h>

#define     LocalStr_None           @""
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@implementation SHJudgeTools

+ (BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


//手机号码验证
+ (NSString *)valiMobile:(NSString *)mobile{
    
    if (mobile.length < 11||mobile.length>11)
    {
        return @"手机号长度只能是11位";
    }else if(mobile.length < 1 || mobile == nil){
        return @"手机号不能为空";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         *联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的电话号码";
        }
    }
    return nil;
}


//车牌号验证
+ (BOOL)validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}


//车型
+ (BOOL)validateCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}


//用户名
+ (BOOL)validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}


//密码
+ (BOOL) validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}


//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}
//图片链接
+ (BOOL)validateImageUrl:(NSString *)url
{
    NSString *CarTypeRegex = @".*!\\d{3}$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:url];
}
+ (BOOL)validCustomStr:(NSString *)str match:(NSString *)match
{
    NSString *CarTypeRegex = match;
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:str];
}

//+ (NSString *)netType
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//   Reachability *reachability = [Reachability reachabilityForInternetConnection];
//    [reachability startNotifier];
//    NetworkStatus status = [reachability currentReachabilityStatus];
//    switch (status) {
//        case NotReachable:
//        {
//           return @"和网络断开连接";
//        }
//            break;
//        case ReachableViaWiFi:
//        {
//            return @"wifi";
//        }
//            break;
//        case ReachableViaWWAN:
//        {
//            return @"蜂窝数据";
//        }
//            break;
//        default:
//            break;
//    }
//
//}
//


/*!
 * Called by Reachability whenever status changes.
 */
- (void) reachabilityChanged:(NSNotification *)note
{
    //    Reachability* curReach = [note object];
    //    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    //    [self updateInterfaceWithReachability:curReach];
}

//- (void)updateInterfaceWithReachability:(Reachability *)reachability
//{
//    NetworkStatus status = [reachability currentReachabilityStatus];
//    switch (status) {
//        case NotReachable:
//        {
//            NSLog(@"和网络断开连接");
//        }
//            break;
//        case ReachableViaWiFi:
//        {
//            NSLog(@"wifi");
//        }
//            break;
//        case ReachableViaWWAN:
//        {
//            NSLog(@"蜂窝数据");
//        }
//            break;
//        default:
//            break;
//    }
//}

//+ (NSDictionary *)getDateAction:(int)number
//{
//    NSTimeInterval late2 = [[NSDate date] timeIntervalSince1970]*1;
//
//    NSLog(@"%f",late2);
//
//    NSTimeInterval cha = late2 - number;
//
//    NSArray * arrWeek=[NSArray arrayWithObjects:@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六", nil];
////    NSLog(@"%l",num);
////    NSDate *dateone = [[NSDate alloc] initWithTimeIntervalSince1970:1453499999];//传人时间戳
//    NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:cha];//传人时间戳
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    //    NSInteger interval = [zone secondsFromGMTForDate: date];
//    //    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
//
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    NSDateComponents * comps = [[NSDateComponents alloc] init];
//    comps.timeZone = zone;
//    NSInteger unitFlags = NSYearCalendarUnit |
//    NSMonthCalendarUnit |
//    NSDayCalendarUnit |
//    NSWeekdayCalendarUnit |
//    NSHourCalendarUnit |
//    NSMinuteCalendarUnit |
//    NSSecondCalendarUnit;
//    comps = [calendar components:unitFlags fromDate:date];
//
//    NSInteger week = [comps weekday];
//    NSInteger day = [comps day];
//    NSInteger year = [comps year];
//    NSInteger month = [comps month];
//    NSInteger hour = [comps hour];
//    NSInteger minute = [comps minute];
//    NSInteger second = [comps second];
//
//    return @{@"day":@(day),@"hour":@(hour),@"minute":@(minute),@"second":@(second),@"week":[arrWeek objectAtIndex:week-1],@"year":@(year),@"month":@(month),@"weekInteger":@(week -1)};
//}

+ (NSDictionary *)getDateAction:(int)number
{
    NSTimeInterval late2 = [[NSDate date] timeIntervalSince1970]*1;
    NSTimeInterval cha = number - late2;
    NSString *timeString = @"";
    NSString *house = @"";
    NSString *min = @"";
    NSString *sen = @"";
    NSString *day = @"";
    sen = [NSString stringWithFormat:@"%2d", (int)cha%60];
    //    秒
    sen=[NSString stringWithFormat:@"%@", sen];
    
    min = [NSString stringWithFormat:@"%2d", (int)cha/60%60];
    //    分
    min=[NSString stringWithFormat:@"%@", min];
    
    //    小时
    house = [NSString stringWithFormat:@"%2d", (int)cha/3600 % 24];
    house=[NSString stringWithFormat:@"%@", house];
    
    //    小时
    day = [NSString stringWithFormat:@"%2d", (int)cha/3600 / 24];
    
    timeString=[NSString stringWithFormat:@"%@:%@:%@:%@",day,house,min,sen];
    
    NSDictionary *dic ;
    if ((int)cha%60 < 0) {
        dic = @{@"day":@"00",
                @"hour":@"00",
                @"min":@"00",
                @"sen":@"00"};
    }else{
        dic = @{@"day":day,
                @"hour":house,
                @"min":min,
                @"sen":sen};
    }
    return dic;
}

+ (NSString *)base64StringFromText:(NSString *)text
{
    if (text && ![text isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY  改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
        //IOS 自带DES加密 Begin  改动了此处
        //data = [self DESEncrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [self base64EncodedStringFrom:data];
    }
    else {
        return LocalStr_None;
    }
}

+ (NSString *)textFromBase64String:(NSString *)base64
{
    if (base64 && ![base64 isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY   改动了此处
        //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
        NSData *data = [self dataWithBase64EncodedString:base64];
        //IOS 自带DES解密 Begin    改动了此处
        //data = [self DESDecrypt:data WithKey:key];
        //IOS 自带DES加密 End
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    else {
        return LocalStr_None;
    }
}

/******************************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES加密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 ******************************************************************************/
+ (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    return nil;
}

/******************************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES解密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 ******************************************************************************/
+ (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    
    free(buffer);
    return nil;
}

/******************************************************************************
 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string
 函数描述 : base64格式字符串转换为文本数据
 输入参数 : (NSString *)string
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 :
 ******************************************************************************/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:nil];
    if ([string length] == 0)
        return [NSData data];
    
    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }
    
    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }
        
        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }
        
        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }
    
    bytes = realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

/******************************************************************************
 函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data
 函数描述 : 文本数据转换为base64格式字符串
 输入参数 : (NSData *)data
 输出参数 : N/A
 返回参数 : (NSString *)
 备注信息 :
 ******************************************************************************/
+ (NSString *)base64EncodedStringFrom:(NSData *)data
{
    if ([data length] == 0)
        return @"";
    
    char *characters = malloc((([data length] + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (i < [data length])
    {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < [data length])
            buffer[bufferLength++] = ((char *)[data bytes])[i++];
        
        //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = encodingTable[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    
    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
}

/**
 *  把字符串加密成32位小写md5字符串
 *
 *  @param inPutText 需要被加密的字符串
 *
 *  @return 加密后的32位小写md5字符串
 */
+ (NSString*)md532BitLower:(NSString *)inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

/**
 *  把字符串加密成32位大写md5字符串
 *
 *  @param inPutText 需要被加密的字符串
 *
 *  @return 加密后的32位大写md5字符串
 */
+ (NSString*)md532BitUpper:(NSString*)inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] uppercaseString];
}

+ (NSString *)secret:(NSString *)Str{
    if (Str!=nil && ![Str isEqualToString:@""]) {
        NSString *base64OneStr = [self base64StringFromText:Str];
        NSString *base64TwoStr = [self base64StringFromText:base64OneStr];
        return [self md532BitUpper:base64TwoStr];
    }else{
        return @"";
    }
    
}

//+(BOOL)valiLocationCanOrNo{
//    if ([CLLocationManager locationServicesEnabled] &&
//        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
//         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
//            //定位功能可用，开始定位
//            return YES;
//        }
//    //    ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
//    else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
//        
//        [KVNProgress showErrorWithStatus:@"您还没有开启定位，请在手机设置中开启定位再使用"];
//        
//        return NO;
//    }else{
//        return YES;
//    }
//}

// 根据日期 判断星期
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

+(void)MBProgressHUDPromptWith:(NSString *)str On:(UIView *)view{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.margin = 10.f;
    hud.yOffset = 100.f;
    hud.labelText = str;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:0.5];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [hud removeFromSuperview];
    });
    
    
}

+(NSDictionary *)deviceWANIPAdress{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
    NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
    //判断返回字符串是否为所需数据
    if ([ip hasPrefix:@"var returnCitySN = "]) {
        //对字符串进行处理，然后进行json解析
        //删除字符串多余字符串
        NSRange range = NSMakeRange(0, 19);
        [ip deleteCharactersInRange:range];
        NSString * nowIp =[ip substringToIndex:ip.length-1];
        //将字符串转换成二进制进行Json解析
        NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        return dict;
    }
    return nil;
}

 //字符串排序
+(NSString *)orderToNsstring:(NSString *)str
{
    NSMutableString * storeStr=[[NSMutableString alloc]init];
    [storeStr appendString:str];
    for (int i=0; i<storeStr.length-1; i++)
    {
        for (int j=0; j<storeStr.length-1-i; j++)
        {
            NSRange rang1={j,1};
            NSRange rang2={j+1,1};
            NSString * str1=[storeStr substringWithRange    :rang1];
            NSString * str2=[storeStr substringWithRange:rang2];
            if ([str1 compare:str2]==NSOrderedDescending)
            {
                [storeStr replaceCharactersInRange:rang1 withString:str2];
                [storeStr replaceCharactersInRange:rang2 withString:str1];
            }
        }
    }
    return storeStr;
}

//划掉原价
+(void)crossOutTheOriginalPrice:(NSString *)price onLabel:(UILabel *)label{
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:price];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, [price length])];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, [price length])];
    [label setAttributedText:attri];
    
}


//sha1加密方式
+(NSString *)getSha1String:(NSString *)srcString{
    const char * cstr = [srcString cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:srcString.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (int)data.length, digest);
    
    NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];
    
    for(int i =0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}


+(NSMutableAttributedString*)changeAllStr:(NSString*)Allstr partStr:(NSString*)partStr color:(UIColor*)Color font:(NSInteger)Font{
    
    
    NSMutableAttributedString *mAttStri = [[NSMutableAttributedString alloc] initWithString:Allstr];
    
    NSRange range = [Allstr rangeOfString:partStr];
    
    [mAttStri addAttribute:NSForegroundColorAttributeName value:Color range:range];
    
    [mAttStri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:Font] range:range];
    
    return mAttStri;
}

+(NSString *)ForTimeZeouStr:(NSString *)timeZeou{

//   NSTimeInterval time=[timeZeou doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    
    NSTimeInterval time=[timeZeou doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate*detaildate=[NSDate  dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];


    return currentDateStr;

}

+(NSString *)ForTimeZoneAndTimeStr:(NSString *)timeZeou {

    NSTimeInterval time=[timeZeou doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate*detaildate=[NSDate  dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    
    
    return currentDateStr;
}

+(NSString *)ForTimeZoneOnlyDay:(NSString *)timeZeou {
    
    NSTimeInterval time=[timeZeou doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate*detaildate=[NSDate  dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"MM-dd"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    
    NSArray * yearArray = [currentDateStr componentsSeparatedByString:@"-"];
    NSString * yearStr =  [yearArray lastObject];
    
    return yearStr;
}

+(NSString *)ForTimeZoneOnlyMonth:(NSString *)timeZeou {

    NSTimeInterval time=[timeZeou doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate*detaildate=[NSDate  dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"MM月"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    
    
    return currentDateStr;

}

+(NSString *)ForTimeZoneOnlyHourandMin:(NSString *)timeZeou{

    NSTimeInterval time=[timeZeou doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate*detaildate=[NSDate  dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"HH:mm"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    
    
    return currentDateStr;
}

#pragma mark - 图片压缩到指定大小(最大值)
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

+(int)totailpageNumberForTotailNumber:(NSString *)numberStr{
    
    int totailPage = 0;
    int a = [numberStr intValue]/10;
    int b =  [numberStr intValue]%10;
    if (a>0&&b>0) {
        totailPage = a+1;
    }
    if (a==0&&b>0) {
        totailPage = 1;
    }
    if (a==0&&b==0) {
        totailPage = 0;
    }
    if (a>0&&b==0) {
        totailPage = a;
    }
    
    return totailPage;
}

//比较两个日期的大小  日期格式为2016-08-14 08：46：20
+ (NSInteger)compareDate:(NSString*)aDate withDate:(NSString*)bDate
{
    NSInteger aa;
    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
    [dateformater setDateFormat:@"yyyy-MM-dd"];
    NSDate *dta = [[NSDate alloc] init];
    NSDate *dtb = [[NSDate alloc] init];
    
    dta = [dateformater dateFromString:aDate];
    dtb = [dateformater dateFromString:bDate];
    NSComparisonResult result = [dta compare:dtb];
    if (result==NSOrderedSame)
    {
        //   相等
        aa=0;
    }else if (result==NSOrderedAscending)
    {
        //a 比 b 小
        aa=1;
    }else
    {
        //a  比 b 大
        aa=-1;
        
    }
    
    return aa;
}



@end
